<?php

namespace app\admin\controller;

use app\common\model\QuAnswer;
use app\common\model\QuClasses;
use app\common\model\QuQuestion;
use app\common\model\QuStudent;
use app\service\MsgService;
use think\Controller;
use app\common\model\Manager as ManagerModel;
use app\common\model\User;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

use GuzzleHttp\Client;
use app\common\model\Config;
use think\Db;


class Login extends Controller
{
    public function __construct()
    {
        parent::__construct();
        config(Config::getConfig());
    }

    public function index()
    {
        $this->assign('data', [
            'type' => 'click',  //展示方式，默认为嵌入式
            'vid' => config('vaptcha_id')
        ]);
        return view();
    }

    public function dologin()
    {
        $input = input();

        if (!$input['name'] || !$input['password']) {
            return returnJson(1, '请填写用户名和密码');
        }
//        if(!$input['token']) {
//            return returnJson(1,'请填写token');
//        };

//        $client = new Client([]);
//        $response = $client->post('http://api.vaptcha.com/v2/validate', [
//            'form_params' => [
//                'id' => config('vaptcha_id'),
//                'secretkey' => config('vaptcha_key'),
//                'scene' => '',
//                'token' => $input['token'],
//                'ip' => ''
//            ]
//        ]);
//        $body = $response->getBody();
//        $result = json_decode((string)$body,true);
//        if($result['success']==0) {
//            return returnJson(1, '验证码错误');
//        }

        $manager = ManagerModel::getOne([
            'name' => $input['name']
        ]);

        if (!$manager || createPassword($input['password']) != $manager['password']) {
            return returnJson(1, '密码错误');
        }


        session('manager', $manager);
        return returnJson(0, '登陆成功', '/w');
    }

    public function quit()
    {
        session('manager', null);
        return returnJson(2, '已退出', '/w');
    }

    public function test()
    {
        //配置模板消息
        MsgService::S([
            'mall_id' => 1
        ])->resetMallTmpl(1);
    }


    public function wenti()
    {
        $qu_ids = QuQuestion::getColumn([], 'id');
        $qu_rand = array_rand($qu_ids, 25);
        foreach ($qu_rand as $value) {
            $qu_idss[] = $qu_ids[$value];
        }


        $qu = QuQuestion::getAll(['id' => ['in', $qu_idss]]);
        foreach ($qu as $key => $value) {
            unset($qu[$key]['id']);
            $qu[$key]['score'] = 4;
            $qu[$key]['aid'] = 15;

        }

        model('qu_question')->insertAll($qu);
    }

    public function stu()
    {
        $path = '1.xls';
        $data = $this->readElsx($path);
        db('qu_student1')->insertAll($data);

    }

    public function student()
    {
        $student1 = db('qu_student1')
            ->where([])
            ->select()
            ->toArray();
        $where = [];
        foreach ($student1 as $value) {
            $where = [
                'name' => $value['name'],
                'num' => $value['num'],
                'cid' => $value['cid']
            ];
            $sid = QuStudent::getValue($where, 'id');
            if ($sid)
                db('qu_student1')->where('id', $value['id'])->update(['id' => $sid]);
        }

    }


    public function readElsx($path)
    {
//        $path = tomedia($path);
        $local_psth = ROOT_PATH . "public" . DS . basename($path);
//        if (copy(trim($path), $local_psth)) {
        $ext = ucfirst(array_pop(explode('.', $local_psth)));
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($ext);
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($local_psth);
        $sheet = $spreadsheet->getSheet(0);
        $highest_row = $sheet->getHighestRow();
//        $highest_row = 3;
        $highest_columm = $sheet->getHighestColumn();
        $actives = [];
        $classes = QuClasses::getColumn([], 'id,sub_name');
        for ($row = 4; $row <= $highest_row; $row++) { //行号从1开始
            $active_row = [
                'update_time' => time(),
                'create_time' => time(),
            ];
            for ($column = 'A'; $column <= $highest_columm; $column++) { //列数是以A列开始
                $active_row[$column] = $sheet->getCell($column . $row)->getValue();
                // switch ($column) {
                //     case 'D':
                //         $active_row['num'] = $sheet->getCell($column . $row)->getValue();
                //         break;
                //     case 'E':
                //         $active_row['name'] = $sheet->getCell($column . $row)->getValue();
                //         break;
                //     case 'H':
                //         $class = $sheet->getCell($column . $row)->getValue();
                //         $active_row['cid'] = in_array($class, $classes) ? array_keys($classes, $class)[0] : 0;
                //         break;
                // }
            }
            if (!in_array($active_row, $actives))
                $actives[] = $active_row;
        }
        return $actives;
//        }
    }


    public function answer_change()
    {
        $answer = QuAnswer::getAll(['aid'=>16]);
        $qu = QuQuestion::getColumn(['aid'=>16],'id,score,right,question');
        foreach ($qu as $k=>$v){
            $qu[$k]['right'] = json_decode($v['right'],true);
        }
        foreach ($answer as $value){
            $score = 0;
            if($value['answer']){
                $answers = json_decode($value['answer'],true);
                foreach ($answers as $k => $val){
                    if(in_array($k,['danxuan','duoxuan','panduan'])){
                        foreach ($val as $valu){
                            pr($qu['question']);
                            if(is_array($valu['answer']) && $valu['answer']==$qu[$valu['qid']]['right']){
                                   $score += $qu[$valu['qid']]['score'];
                            } else if([$valu['answer']]==$qu[$valu['qid']]['right']){
                                   $score += $qu[$valu['qid']]['score'];
                            }
                        }

                    }
                }

            }
            pr($value['id']. ':'.$score);
        }
    }


    public function student1(){
        $student2 = Db::table('zkhb_qu_student2')->where(cid,'>',40)->select()->toArray();
        foreach ($student2 as $key => $value){
            if(QuStudent::getOne(['name'=>$value['name'],'num' =>$value['num']])){
                unset($student2[$key]);
            }
        }
        $sids = QuStudent::getAll(['id'=>['in',array_column($student2,'id')]]);
        if(!$sids){
            foreach ($student2 as $value){
//                QuStudent::create($value);
            }
        }

//        pr($sids);
//        pr(sizeof($student2));
        _pr($student2);

    }


    public function data()
    {
//        $classes = QuClasses::getColumn(['id'=>['>',82]],'name,id');
//        $data = $this->readElsx('1.xlsx');
//        foreach($data as $value) {
//
            $save_data = [
                'num' => '202082885',
                'name' => '宋豫',
                'cid' => 135,
                'update_time' => time(),
                'create_time' => time(),
            ];
//            _pr($save_data);die;
            db('qu_student')->insert($save_data);
//            QuClasses::create($save_data);
//        }
//        _pr($data);

    }

}
